﻿function item(id, name) {
    this.id = ko.observable(id);
    this.name = ko.observable(name);
}

function mailerViewModel(campaignId) {

    this.error = ko.observable("");

    this.campaign = ko.observable(new item("-", "-"));
    this.selectedCampaignActivity = ko.observable();
    this.selectedList = ko.observable();

    this.campaignActivities = ko.observableArray([]);
    this.lists = ko.observableArray([]);

    this.subject = ko.observable("Radikal Mailer test");
    this.body = ko.observable("<html><body><h1>Hello: #FullName# </h1><h2>#ContactId#</h2></body></html>");

    this.inProgress = ko.observable(false);
    this.all = ko.observable(0);
    this.processed = ko.observable(0);
    this.errors = ko.observable(0);
    this.currentCustomer = ko.observable("-");

    this.load = function (campaignId) {
        retrieveRecord(campaignId, "CampaignSet", jQuery.proxy(this.SetCampaign, this), jQuery.proxy(this.HandleError, this));

        // /CampaignActivitySet?$filter=RegardingObjectId/Id eq guid'D061F52C-1AF0-E011-82F5-001A4BE88E88'
        retrieveMultiple("CampaignActivitySet", "?$filter=RegardingObjectId/Id eq guid'" + campaignId + "'", jQuery.proxy(this.SetCampaignActivities, this), jQuery.proxy(this.HandleError, this))

        // /CampaignSet?$select=campaignlist_association/ListId,campaignlist_association/ListName&$expand=campaignlist_association&$filter=CampaignId eq guid'D061F52C-1AF0-E011-82F5-001A4BE88E88'
        retrieveMultiple("CampaignSet?$select=campaignlist_association/ListId,campaignlist_association/ListName&$expand=campaignlist_association", "&$filter=CampaignId eq guid'" + campaignId + "'", jQuery.proxy(this.SetLists, this), jQuery.proxy(this.HandleError, this))
    }

    this.SetCampaign = function (campaign) {
        this.campaign().id(campaign.CampaignId);
        this.campaign().name(campaign.Name);
    }

    this.SetCampaignActivities = function (activities) {
        this.campaignActivities.remove(function (item) { return true; })

        for (var i = 0; i < activities.length; i++) {
            this.campaignActivities.push(new item(activities[i].ActivityId, activities[i].Subject));
        }
    }

    this.SetLists = function (lists) {
        this.lists.remove(function (item) { return true; })

        var ls = lists[0].campaignlist_association.results;
        for (var i = 0; i < ls.length; i++) {
            this.lists.push(new item(ls[i].ListId, ls[i].ListName));
        }
    }

    this.startProcessing = function () {
        this.inProgress(true);

        var columns = ['EntityId', 'EntityType'];
        var filter = "ListId/Id eq guid'" + this.selectedList().id() + "'";

        var collection = CrmRestKit.RetrieveMultiple('ListMember', columns, filter);
        this.ProcessListMembers(collection.results);

        while (collection.next) {
            // laod next 50 records
            var collection = collection.LoadNext();
            this.ProcessListMembers(collection.results);
        }

        // finished
        this.inProgress(false);
    }

    this.ProcessListMembers = function (listmembers) {

        this.all(this.all() + listmembers.length);
        

        for (var i = 0; i < listmembers.length; i++) {
            try {

                etn = capitaliseFirstLetter(listmembers[i].EntityId.LogicalName)

                // load customer
                var c = retrieveRecordSync(listmembers[i].EntityId.Id, etn + "Set"); // listmembers[i].EntityType

                // this.currentCustomer(c.FullName);

                // create mail 
                var email = new Object();
                email.Subject = this.subject();


                var b = this.body();
                var re = /#\w*#/g;
                var result = b.match(re);

                for (var index = 0; index < result.length; index++) {
                    key = result[index].substr(1, result[index].length - 2);
                    b = b.replace(result[index], eval("c." + key));
                }

                email.Description = b;

                email.RegardingObjectId = { Id: this.selectedCampaignActivity().id(), LogicalName: "campaignactivity" };
                var activity = createRecordSync(email, "EmailSet");

                // set ToRecipient
                var activityParty = new Object();
                activityParty.PartyId = { Id: eval("c." + etn + "Id"), LogicalName: listmembers[i].EntityId.LogicalName };
                activityParty.ActivityId = { Id: activity.ActivityId, LogicalName: "email" };
                activityParty.ParticipationTypeMask = { Value: 2 }; // 2 = ToRecipients 
                createRecordSync(activityParty, "ActivityPartySet");

                // set FromRecipient
                var activityParty = new Object();
                activityParty.PartyId = { Id: context.getUserId(), LogicalName: "systemuser" };
                activityParty.ActivityId = { Id: activity.ActivityId, LogicalName: "email" };
                activityParty.ParticipationTypeMask = { Value: 1 }; // 1 = Sender 
                createRecordSync(activityParty, "ActivityPartySet");

                // send (cant do it using rest :-( )

                sendEmail(activity.ActivityId);

            }
            catch (e) {
                this.errors(this.errors() + 1);
            }
            this.processed(this.processed() + 1);
        }

        
    }

    this.pauseProcessing = function () {
        this.inProgress(false);
    }

    this.cancelProcessing = function () {
        this.inProgress(false);
    }

    this.HandleError = function (e) {
        var err = "unknown error";

        if (e.statusText != undefined)
            err = FormatDateTime(new Date()) + ": " + e.status + '; ' + e.statusText + '; ' + e.responseText; // soap
        else if (e.message != undefined)
            err = FormatDateTime(new Date()) + ": " + e.message + '; ' + e.number + '; ' + e.description; // jscript
        else
            err = e;

        this.error(err)
    }

    this.load(campaignId);
}


$(function () {

    jQuery.support.cors = true;

    var _campaignId = "D061F52C-1AF0-E011-82F5-001A4BE88E88"; // TODO read from query string 
    // var _campaignId = ($.QueryString["id"] );
    // _campaignId = _campaignId.substr(1, _campaignId.length-2);

    alert(_campaignId)

    ko.applyBindings(new mailerViewModel(_campaignId));

});


function capitaliseFirstLetter(string) {
    return string[0].toUpperCase() + string.slice(1);
} 

(function ($) {
    $.QueryString = (function (a) {
        if (a == "") return {};
        var b = {};
        for (var i = 0; i < a.length; ++i) {
            var p = a[i].split('=');
            if (p.length != 2) continue;
            b[p[0]] = decodeURIComponent(p[1].replace(/\+/g, " "));
        }
        return b;
    })(window.location.search.substr(1).split('&'))
})(jQuery);